package com.soap.util;

import org.lionsoul.ip2region.xdb.Searcher;
import org.lionsoul.ip2region.xdb.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class IPSearch {
    private static Logger logger = LoggerFactory.getLogger(IPSearch.class);
    /**
     *   在服务启动时加载 ip2region.db 到内存中
     *   解决打包jar后找不到 ip2region.db 的问题
     */
    // 1、使用上述的 version 和 dbPath 创建 searcher 对象
    private static Searcher searcher = null;
    static {
        try {
            Path resourcePath = Paths.get(IPSearch.class.getClassLoader().getResource("ipdb/ip2region_v4.xdb").toURI());
            String path = resourcePath.toAbsolutePath().toString();
            logger.debug("ip2region.db path: {}", path);
            searcher = Searcher.newWithFileOnly(Version.IPv4,resourcePath.toAbsolutePath().toString());
            //注意：不能使用文件类型，打成jar包后，会找不到文件
            logger.debug("缓存成功！！！！");
        } catch (IOException | URISyntaxException e) {
            logger.error("解析ip地址失败,无法创建搜索器: {}", e);
            throw new RuntimeException(e);
        }
    }

   public static String getIpInfo(String ip) {
        try {
            return searcher.search(ip);
        } catch (Exception e) {
            logger.error("解析ip:{}地址失败: {}",ip, e);
        }
        return "";
    }
}
